import { MaterialIcons } from 'taro-icons';
import Taro, { useRouter } from '@tarojs/taro';
import { View, Text } from '@tarojs/components';
import React, { useState, useRef, useEffect } from 'react';

import PageHeader from '../../components/pageHeader';
import { useAppContext } from '../../contexts/AppContext';
import ProcessStatus from '../../components/processStep/processStatus';
import { CompleteButton, NextButton } from '../../components/processStep/processButton';
import { getUserProgressStepApi, setUserProgressStepStatusApi, getMyInterviewResultApi } from '../../api/myself';

import './index.scss';

/**
 * 用户预约面签页面
 * 展示用户的面签预约信息和功能
 */
const UserInterviewPage: React.FC = () => {
  const router = useRouter();
  const firstLoadRef = useRef<boolean>(false);
  const stepId = router.params.stepId as string;
  const [appointAddress, setAppointAddress] = useState(' ');
  const [appointDate, setAppointDate] = useState(' ');
  const [userStep, setUserStep] = useState<any>({
    id: 0, name: "", children: [], completed_time: "", status: 0
  });
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const { userInfo, setCarSubjectStepProcessStatus } = useAppContext();

  // 获取初始化信息
  const getInitInfoData = async () => {
    try {
      const res = await getUserProgressStepApi(Number(stepId));
      if (res.code === 200 && res.data && res.data.length === 1) {
        const result = res.data[0];
        setUserStep({
          id: stepId,
          name: result.name,
          status: result.status,
          completed_time: result.created_at,
          children: result.children?.split(',') || [],
        });
        if (result.status === 1) {
          getMyInterviewResult();
        }
      }
    } catch (err) {
      console.log(err);
      Taro.showToast({ title: '获取用户进度失败', icon: 'none' });
    }
  };

  const updateStepStatus = async () => {
    try {
      setIsLoading(true);
      const res = await setUserProgressStepStatusApi(Number(stepId), 2);
      if (res.code === 200) {
        Taro.showToast({ title: '预约申请已发送，请耐心等待教练处理~', icon: 'success' });
        setUserStep({
          ...userStep,
          status: 2
        });
        setCarSubjectStepProcessStatus(Number(stepId), 2);
      }
    } catch (err) {
      console.log(err);
      Taro.showToast({ title: '预约失败，请稍后重试~', icon: 'none' });
    } finally {
      setIsLoading(false);
    }
  };

  const getMyInterviewResult = async () => {
    try {
      const res = await getMyInterviewResultApi();
      if (res.code === 200 && res.data) {
        setAppointAddress(res.data.address);
        setAppointDate(res.data.date);
      }
    } catch (err) {
      console.log(err);
      Taro.showToast({ title: '获取预约信息失败', icon: 'none' });
    }
  };

  useEffect(() => {
    if (!stepId) return;
    if (!firstLoadRef.current) {
      firstLoadRef.current = true;
      getInitInfoData();
    }
  }, []);

  // 获取状态文本
  const getStatusText = () => {
    switch (userStep.status) {
      case 0:
        return '未预约';
      case 1:
        return '已预约';
      case 2:
        return '预约中...';
      default:
        return '未预约';
    }
  };

  const handleContinueNextStep = () => {
    Taro.navigateTo({
      url: `/pages/user-study-time/index?stepId=${stepId}&tab=1`
    });
  }

  return (
    <View className="page-container user-interview-page">
      {/* 顶部导航栏 */}
      <PageHeader title="预约面签" />
      
      {userStep.completed_time && (
        <ProcessStatus title={userStep.name} createTime={userStep.completed_time} />
      )}
      
      {/* 预约面签标题卡片 */}
      <View className="interview-card">
        <View className="card-header">
          <View className="header-text">预约面签</View>
          <View className="interview-status blue-color text-md">{getStatusText()}</View>
        </View>
        
        <View className="card-content">
          <View className="greeting-section">
            <Text className="user-name">{userInfo?.username}:</Text>
            <View className="greeting-text text-base">
              <Text>&emsp;您好，抱歉让您久等了。请于</Text>
              <Text className="appoint-date text-md">{appointDate}&emsp;上午9点到下午3点钟之间</Text>
              <Text>。&emsp;请您带好您的 &emsp;</Text>
            </View>
            
            <View className="documents-section text-base">
              
              <View className="tag-container">
                <View className="purple-tag text-md">有效身份证原件</View>
                <View className="lime-tag text-md">驾驶员体检照片</View>
                <View className="cyan-tag text-md">体检自述身体报告单</View>
              </View>
              
              <View className="note-section">
                <MaterialIcons name="info" color="#fa8c16" size={20} />
                <Text className="note-text text-base">体检自述身体报告单没有没关系，可以现场填写。</Text>
              </View>
            </View>
            
            <Text className='info-text text-base'>&emsp;辛苦前往<Text className="address-text text-md">{appointAddress}</Text>进行面签</Text>
          </View>
          
          {/* 信息卡片 */}
          <View className="info-grid">
            <View className="info-item">
              <MaterialIcons name="place" color="#f5222d" size={20} />
              <Text className="info-text text-base">{appointAddress}</Text>
            </View>
            <View className="info-item">
              <MaterialIcons name="event" color="#1890ff" size={20} />
              <Text className="info-text text-base">{appointDate}</Text>
            </View>
            <View className="info-item">
              <MaterialIcons name="access-time" color="#52c41a" size={20} />
              <Text className="info-text text-base">9:00-15:00</Text>
            </View>
            <View className="info-item">
              <MaterialIcons name="credit-card" color="#f5222d" size={20} />
              <Text className="info-text text-base">身份证原件</Text>
            </View>
            <View className="info-item">
              <MaterialIcons name="image" color="#1890ff" size={20} />
              <Text className="info-text text-base">驾驶员体检照片</Text>
            </View>
            <View className="info-item">
              <MaterialIcons name="description" color="#52c41a" size={20} />
              <Text className="info-text text-base">体检自述身体报告单</Text>
            </View>
          </View>
        </View>
        
        {/* 底部提示 */}
        <View className="reminder-section">
          <Text className="reminder-text text-base">请提前15分钟到达现场，逾期不候</Text>
        </View>

          {/* 特别注意 */}
          <View className="study-time-notice">
            <View className="notice-title">
              <MaterialIcons name="info" color="#e6a23c" className="mr-2" size={16} />
              <Text className="notice-title-text text-lg">特别注意</Text>
            </View>
            <View className="notice-content">
              <Text className='text-md'>如您已有其他类型的驾照，请确认该驾照的核发地与您当前所在城市是否一致。</Text>
              <Text className='text-md'>如果两者不在同一个城市，请登录交管12123，先申请 驾照转入该城市</Text>
            </View>
          </View>

      </View>
      
      {/* 底部按钮 */}
      {userStep.status === 0 ? (
        <View className="button-section">
            <CompleteButton disabled={isLoading} loading={isLoading} onClick={updateStepStatus} content="申请预约面签" />
            <Text className="note-text mt-5 text-base">预约后，由教练就近分配面签地点</Text>
        </View>
      ): (
        <View className="user-drive-hospital-completion-section">
          <NextButton onClick={handleContinueNextStep}/>
        </View>
      )}
    </View>
  );
};

export default UserInterviewPage;